package app.controllers.member;

import app.Const;
import app.constant.MemberConstant;
import app.kit.SmsCodeKit;
import app.kit.SmsKit;
import app.models.member.Account;
import app.models.member.Member;
import app.models.member.MemberProduct;
import app.models.order.Order;
import app.models.member.RedeemProduct;
import app.models.product.Product;
import app.services.OrderService;
import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import goja.StringPool;
import goja.mvc.Controller;
import goja.security.goja.SecurityKit;
import org.joda.time.DateTime;

import java.sql.SQLException;

/**
 * <p>
 * The url member/redemption Controller.
 * 产品赎回流程
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class RedemptionController extends Controller {

    /**
     * The index route.
     * the url /member/redemption
     * the view in index.ftl
     * <p/>
     * 赎回确认信息，进行交易密码验证
     */
    public void index() {
        int memberProductId = getParaToInt(0, 0);
        if (memberProductId > 0) {
            MemberProduct memberProduct = MemberProduct.dao.findById(memberProductId);
            if (memberProduct == null) {
                renderError(404);
            } else {
                setAttr("memberProduct", memberProduct);
            }
        } else {
            renderError(404);
        }
    }


    /**
     * 发送验证码
     */
    public void send(){
        final Member loginUser = SecurityKit.getLoginUser(getRequest());
        SmsKit.redemption(loginUser.getStr("phone"));
        renderAjaxSuccess();
    }


    public void verification() {
        // 短信验证码
        String sms_code = getPara(Const.FIELD_CODE);
        if (Strings.isNullOrEmpty(sms_code)) {
            renderAjaxFailure("请输入短信验证码");
            return;
        }

        final Member loginUser = SecurityKit.getLoginUser(getRequest());
        String phone = loginUser.getStr("phone");
        if (!SmsCodeKit.checkRedemption(phone, sms_code)) {
            renderAjaxFailure("短信验证码不正确");
            return;
        }

        // 交易密码
        String password = getPara("pwd");

        if (!Strings.isNullOrEmpty(password)) {
            final int memberId = loginUser.getNumber(StringPool.PK_COLUMN).intValue();
            final Account account = Account.dao.findbyMember(memberId);
            boolean matcher = account.checkTradePwd(password);
            if (matcher) {
                renderAjaxSuccess();
            } else {
                renderAjaxFailure("交易密码不正确");
            }
        } else {
            renderAjaxFailure("交易密码不能为空");
        }


    }


    public void success() {
        final Member loginUser = SecurityKit.getLoginUser(getRequest());
        int memberProductId = getParaToInt(0, 0);
        if (memberProductId > 0) {
            final MemberProduct memberProduct = MemberProduct.dao.findById(memberProductId);
            if (memberProduct == null) {
                renderError(404);
            } else {
                final int memberId = loginUser.getNumber(StringPool.PK_COLUMN).intValue();
                final int productId = memberProduct.getNumber(Const.FIELD_PRODUCT).intValue();

                final Product product = Product.dao.findById(productId);

                final String productCode = product.getStr(Const.FIELD_CODE);
                final double amount = memberProduct.getNumber(Const.FIELD_AMOUNT).doubleValue();
                final String productName = product.getStr(Const.FIELD_NAME);

                final DateTime now_time = DateTime.now();

                final Order order = OrderService.me.createRpnOrder(memberId, productId, productName, productCode, amount);

                final RedeemProduct redeemProduct = new RedeemProduct();
                redeemProduct.set(Const.FIELD_MEMBER, memberId);
                redeemProduct.set("member_product", memberProductId);
                redeemProduct.set(Const.FIELD_PRODUCT, productId);
                redeemProduct.set("product_name", productName);
                redeemProduct.set("product_code", productCode);
                redeemProduct.set("phone", loginUser.getStr("phone"));
                redeemProduct.set(Const.FIELD_AMOUNT, amount);
                redeemProduct.set("redeem_time", now_time);
                redeemProduct.set("redeem_time_year", now_time.getYear());
                redeemProduct.set("redeem_time_month", now_time.getMonthOfYear());
                redeemProduct.set("redeem_time_day", now_time.getDayOfMonth());
                redeemProduct.set(Const.FIELD_STATUS, MemberConstant.REDEM_START);
                redeemProduct.set(Const.FIELD_CREATE_TIME, now_time);

                Db.tx(new IAtom() {
                    @Override
                    public boolean run() throws SQLException {

                        if (order.save()) {

                            redeemProduct.set("order_id", order.getBigDecimal(StringPool.PK_COLUMN));
                            // 赎回申请
                            memberProduct.set(MemberProduct.FIELD_REDEEM_STATUS, MemberConstant.REDEEM_AUDIT);
                            return redeemProduct.save() && memberProduct.update();
                        }

                        return false;
                    }
                });
                setAttr("order", order);

            }
        } else {
            renderError(404);
        }
    }
}